﻿#include "guild_building_logic.h"

#include "GuildBuilding_struct.h"
#include "GuildModuleBuilding_struct.h"

#include "error/make_error_code.h"
#include "guild/module/guild_module.h"
#include "guild/module/guild_module_loader.hpp"
#include "guild/module/guild_module_saver.hpp"
#include "guild/guild_loader.hpp"

#include "timer/guild_building_timer.h"
#include "timer/service_timer_mgr.hpp"

namespace guild_service {
bool GuildModuleBuildingLogic::BuildingUpgrade(const guild_id_type guild_id,
                                               uint32_t building_id,
                                               error_code &ec) {
  if (guild_id == kInvalidGuildId) {
    ec = ErrorCode::ERR_INVALID_GUILD_ID;
    return false;
  }
  GuildModuleBuilding module_building;
  if (!detail::GetGuildModule<GuildModuleBuilding>(
          kGuildServiceTimerName, guild_id, kGuildModuleBuildingName,
          module_building)) {
    ec = ErrorCode::ERR_GUILD_MOD_BUILDING_LOAD_FAILED;
    return false;
  }

  auto &building_dic = module_building.building_dic;
  const auto it = building_dic.find(building_id);
  if (it == building_dic.end()) {
    ec = ErrorCode::ERR_GUILD_MOD_BUILDING_BUILDING_NOT_EXIST;
    return false;
  }

  time_scheduler_handler_type handle =
      ServiceTimerMgrSingleton().add_timer<GuildBuildingUpgradeTimer>(guild_id, building_id);

#ifdef DEBNUG
  assert(handle != 0);
#endif // DEBUG
  if (handle == kInvalidTimeHandler) {
    ec = ErrorCode::ERR_GUILD_MOD_BUILDING_UPGRADE_FAILED;
    return false;
  }

  it->second.is_upgrading = true;

  if (!detail::SaveGuildModule<GuildModuleBuilding>(kGuildServiceTimerName,
                                               module_building, guild_id,
                                               kGuildModuleBuildingName)) {
    ec = ErrorCode::ERR_GUILD_MOD_BUILDING_SAVE_FAILED;
    return false;
  }

  return true;
}
}  // guild_service